package com.cloud.controller;

import com.cloud.model.system.SysRole;
import com.cloud.service.SysResourceService;
import com.cloud.service.SysRoleService;
import com.cloud.utils.Result;
import com.cloud.utils.ResultUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by mj on 2017/3/29.
 */
@RestController
public class SysRoleController {
    Logger logger = LoggerFactory.getLogger(SysRoleController.class);
    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysResourceService sysResourceService;

    /**
     * 带分页查询
     *
     * @param sysRole
     * @param page
     * @param size
     * @return
     */
    @GetMapping(value = "roles")
    public Page<SysRole> findWithPaging(SysRole sysRole, @RequestParam(value = "page",
            defaultValue = "0")int page,@RequestParam(value = "size",defaultValue = "10") int size) {
      return sysRoleService.findAll(sysRole,page,size);
    }

    /**
     * 添加角色
     *
     * @param
     * @return
     */
    @PostMapping(value = "roles")
    public Result<SysRole> addRole(@Valid SysRole sysRole, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultUtils.error(bindingResult.getFieldError().getDefaultMessage());
        }
        try {
            sysRole = sysRoleService.addRole(sysRole);
            return ResultUtils.success("添加角色成功", sysRole);
        } catch (Exception e) {
            logger.error("添加角色失败={}", e.getMessage());
            return ResultUtils.error("添加角色失败");
        }
    }

    /**
     * 删除角色
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "roles/{ids}")
    public Result<SysRole> deletRole(@PathVariable String ids) {
        if (StringUtils.isNotBlank(ids)) {
            try {
                String[] idArrayList = ids.split(",");
                List<SysRole> list = new ArrayList<>();
                for (int i = 0; i < idArrayList.length; i++) {
                    SysRole sysRole = new SysRole();
                    sysRole.setId(Long.valueOf(idArrayList[i]));
                    list.add(sysRole);
                }
                sysRoleService.delete(list);
                return ResultUtils.success("删除角色成功");
            } catch (Exception e) {
                logger.error("删除角色失败={}", e.getMessage());
                return ResultUtils.error("删除角色失败");
            }
        } else {
            return ResultUtils.error("删除角色失败");
        }
    }
}
